package com.qf.utils;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@Data
@ConfigurationProperties(prefix = "alipay")
public class AliPayTools {
    private String url;
    private String appid;
    private String privatekey;
    private String publickey;
    private String signtype;
    private String format;
    private String charset;

    //通过配置，动态构建出一个支付宝的登录页面form
    public  String pay(String oid,double price) {
        AlipayClient alipayClient = new DefaultAlipayClient(url, appid, privatekey, format, charset, publickey, signtype);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();

        //异步接收地址，仅支持http/https，公网可访问
        //调用后端接口，修改订单状态 post
        request.setNotifyUrl("http://3pfwed.natappfree.cc/order/status");
        //同步跳转地址，仅支持http/https
        //直接跳转前端页面地址 get
        request.setReturnUrl("http://10.35.186.21:8081/#/paysuccess");
        /******必传参数******/
        JSONObject bizContent = new JSONObject();
//商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", oid);
//支付金额，最小值0.01元
        bizContent.put("total_amount", price);
//订单标题，不可使用特殊符号
        bizContent.put("subject", "测试商品");
//电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizContent.toString());
        try {
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            String form = response.getBody(); //返回一个表单页面(含有支付宝的账号输入信息)
            return form;
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }
}
